﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Tzc_VoteSys.Models.Database;
using Tzc_VoteSys.Service;


namespace Tzc_VoteSys.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Tzc_VoteSysContext _db;
        private readonly IUsers _user;
        //注入JWT服务
        private readonly IJWTService _jwtService;
        public UserController(Tzc_VoteSysContext db, IUsers user, IJWTService jwtService)
        {
            _db = db;
            _user = user;
            _jwtService = jwtService;
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public string Register(string email, string password, string password2)
        {

            if (email != null && password == password2)
            {
                if (_user.ExistEmail(email))
                    return "用户已存在!请不要重复注册";
                _db.Users.Add(new User()
                {

                    Email = email,
                    Password = password,

                });
                var row = _db.SaveChanges();
                if (row > 0)
                {
                    return "用户注册成功";
                }
            }
            return "用户注册失败,两次密码输入不一致";

        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]

        public string Login(string email, string password)
        {
            var user = _db.Users.FirstOrDefault(x => x.Email == email && x.Password == password);
            if (user != null)
            {
                var Token = _jwtService.CreateToken(user.UserId, user.Email);
                return "你好!,Token值为：" + Token;
            }
            return "登录错误！请重新输入";
        }



    }
}
